from sklearn.datasets import load_boston
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LinearRegression,SGDRegressor,Ridge
from sklearn.metrics import mean_squared_error

def linear1():
    boston = load_boston()

    x_train,x_test,y_train,y_test = train_test_split(boston.data,boston.target,random_state=22)

    transfer = StandardScaler()
    x_train = transfer.fit_transform(x_train)
    x_test =transfer.transform(x_test)

    estimator = LinearRegression()
    estimator.fit(x_train,y_train)
    print("正规方程权重系数：\n",estimator.coef_)
    print("正规方程偏置：\n",estimator.intercept_)

    y_predict = estimator.predict(x_test)
    print("房价预测：\n",y_predict)
    error = mean_squared_error(y_test,y_predict)
    print("正规方程均方根误差：\n", error)
    return None

def linear2():
    boston = load_boston()

    x_train,x_test,y_train,y_test = train_test_split(boston.data,boston.target,random_state=22)

    transfer = StandardScaler()
    x_train = transfer.fit_transform(x_train)
    x_test =transfer.transform(x_test)

    estimator = SGDRegressor(learning_rate="constant",eta0=0.01,max_iter=10000)
    estimator.fit(x_train,y_train)
    print("梯度下降权重系数：\n",estimator.coef_)
    print("梯度下降偏置：\n",estimator.intercept_)

    y_predict = estimator.predict(x_test)
    print("房价预测：\n", y_predict)
    error = mean_squared_error(y_test, y_predict)
    print("梯度下降均方根误差：\n", error)
    return None

def linear3():
    boston = load_boston()

    x_train,x_test,y_train,y_test = train_test_split(boston.data,boston.target,random_state=22)

    transfer = StandardScaler()
    x_train = transfer.fit_transform(x_train)
    x_test =transfer.transform(x_test)

    estimator = Ridge(alpha=0.5,max_iter=10000)
    estimator.fit(x_train,y_train)
    print("岭回归权重系数：\n",estimator.coef_)
    print("岭回归偏置：\n",estimator.intercept_)

    y_predict = estimator.predict(x_test)
    print("房价预测：\n", y_predict)
    error = mean_squared_error(y_test, y_predict)
    print("岭回归均方根误差：\n", error)
    return None

if __name__ == '__main__':
    linear1()
    linear2()
    linear3()

